<template>
  <div class="app-container-flex">
    <NewFullScreen
      v-model="showDialog"
      title="根据销售单导入"
      :btn-list="fullInfo.btnList"
    >
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <PageForm
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            :data="formInfo.data"
            :field-list="formInfo.fieldList"
            :rules="formInfo.rules"
            :label-width="formInfo.labelWidth"
          />
        </div>
      </div>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('detailInfo') }}</p>
        </div>
        <div class="model-panel-body">
          <NewPageFilter :filter-btn="filterInfo.btnList">
            <template v-slot:filter-removeProduct>
              <el-button
                :disabled="!tableInfo.selections.length"
                @click="removeProduct"
                >删除</el-button
              >
            </template>
          </NewPageFilter>
          <div>
            <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
              <PageTable
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :summary="true"
                :tab-index="false"
                :check-box="true"
                :summary-field-list="tableInfo.summaryFieldList"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                @handleEvent="handleEvent"
              >
                <template v-slot:col-qty="scope">
                  <el-input-number
                    v-model.lazy="scope.row.qty"
                    clearable
                    controls-position="right"
                    :precision="0"
                    :min="0"
                    :max="scope.row.deliverableQty"
                  />
                </template>
                <template v-slot:col-price="scope">
                  <el-form-item
                    :prop="'data.' + scope.$index + '.price'"
                    style="margintop: 18px"
                    :rules="[
                      {
                        required: scope.$index >= 0,
                        message: '请输入结算单价',
                        trigger: 'blur',
                      },
                    ]"
                  >
                    <el-input-number
                      v-model="scope.row.price"
                      :precision="systemConfig.assets_price_precision"
                      :max="999999999999999"
                      controls-position="right"
                      :min="0"
                    ></el-input-number>
                  </el-form-item>
                </template>
              </PageTable>
            </el-form>
          </div>
        </div>
      </div>
    </NewFullScreen>
    <AddProduct
      v-if="productInfo.visible"
      v-model:query="productInfo.query"
      v-model:show-dialog="productInfo.visible"
      @callback="selectProduct"
    />
  </div>
</template>
<script setup name="deliverOrderModify">
import AddProduct from './deviceAddProduct'
import {
  getDeliverDetailBySaleId,
  addDeliverOrder,
  getDeliverOrderById,
  updateDeliverOrder,
  mergeDeliverOrderDetail,
} from '@/api/supplier.js'

const { proxy } = getCurrentInstance()
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  saleOrderId: {
    type: [Number, String],
  },
  orderId: {
    type: [Number, String],
  },
})
const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const productionTimePickerOptions = ref({
  disabledDate(time) {
    return time.getTime() > Date.now() - 8.64e6
  },
})
const validityTimePickerOptions = ref({
  disabledDate(time) {
    return time.getTime() < Date.now()
  },
})
const fullInfo = ref({
  btnList: [{ label: '保存', event: save, show: true }],
})
const formInfo = ref({
  ref: null,
  data: {
    hospitalId: '',
    expectedDeliverTime: '',
    deptId: '',
  },
  fieldList: [
    {
      label: '客户',
      value: 'hospitalName',
      type: 'input',
      disabled: true,
    },
    {
      label: '客户部门',
      value: 'deptName',
      type: 'input',
      disabled: true,
    },
    {
      label: '预计发货日期',
      value: 'expectedDeliverTime',
      type: 'date',
      dateType: 'date',
      valueFormat: 'YYYY-MM-DD',
      TimePickerOptions: {
        // 限制收货时间不让选择今天以前的
        disabledDate(time) {
          return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
        },
      },
    },
    {
      label: '收货人',
      value: 'receiveContacts',
      type: 'input',
      disabled: true,
    },
    {
      label: '收货电话',
      value: 'receivePhone',
      type: 'input',
      disabled: true,
    },
    {
      label: '收货地址',
      value: 'receiveAddress',
      type: 'input',
      disabled: true,
    },
    { label: '发票号码', value: 'invoiceNumber', type: 'input' },
    { label: '货单号码', value: 'waybillNumber', type: 'input' },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
  ],
  rules: {
    expectedDeliverTime: [
      { required: true, message: '请选择发货日期', trigger: 'blur' },
    ],
    receivePhone: [{ validator: proxy.$validate.cellphone, trigger: 'blur' }],
  },
  labelWidth: '120px',
})
const isUpdate = ref(true)
const formRefs = ref(null)
// 过滤相关配置
const filterInfo = ref({
  query: {
    saleId: props.saleOrderId,
  },
  btnList: [
    {
      type: 'button',
      label: '添加设备',
      event: addProduct,
    },
    {
      type: 'slot',
      label: '删除设备',
      value: 'removeProduct',
    },
  ],
})
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'price', show: 'false' },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [
    {
      label: '设备名称',
      value: 'commonName',
    },
    {
      label: '设备编码',
      value: 'productCode',
    },
    {
      label: '设备规格',
      value: 'standard',
    },
    {
      label: '设备品牌',
      value: 'trademark',
    },
    {
      label: '厂家名称',
      value: 'brandName',
    },
    {
      label: '设备类别',
      value: 'deviceTypeValue',
    },
    {
      label: '可发数量数',
      value: 'deliverableQty',
      type: 'column',
    },
    {
      label: '发货数量',
      value: 'qty',
      type: 'slot',
      width: 250,
    },
    {
      label: '单价',
      value: 'price',
      type: 'slot',
      width: 148,
    },
    {
      label: '总金额',
      value: 'sumAmount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
    },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '50',
    btList: [
      {
        label: '删除',
        event: removeProduct,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: true,
      },
    ],
  },
})
const productInfo = ref({
  visible: false,
  query: {
    saleId: '',
    deliverId: '',
    productIdNotIn: [],
  },
})
const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    proxy.$emit('update:visible', val) // 更新父组件visible
  },
})
watch(
  () => tableInfo.value.data,
  (val) => {
    if (val.length) {
      val.forEach((row) => {
        row['sumAmount'] = proxy.$fn.accMul(row.qty || 0, row.price || 0)
      })
    }
  },
  { deep: true }
)

function compare(property) {
  return function (a, b) {
    return a[property] - b[property]
  }
}

function save() {
  proxy.$fn.checkForm(formRefs.value).then(() => {
    let api = undefined
    if (props.saleOrderId) {
      api = addDeliverOrder
    } else if (props.orderId) {
      api = updateDeliverOrder
    }
    let details = proxy.$fn.deepClone(tableInfo.value.data)
    if (!details.length) {
      proxy.$message({
        message: '请添加设备',
        type: 'warning',
        duration: 3500,
        showClose: true,
      })
      return
    }
    let detailsList = details
      .filter((item) => item.qty <= 0 || !item.qty)
      .map((item) => item.commonName)
    if (detailsList.length) {
      proxy.$alert(`设备【${detailsList}】你还未处理`, '操作提示', {
        confirmButtonText: '确定',
      })
      return
    }
    details.forEach((item) => {
      item.calcQty = item.qty
    })
    const _formInfo = { ...formInfo.value.data, mergeDetails: details }
    if (
      !formInfo.value.data.invoiceNumber ||
      !formInfo.value.data.waybillNumber
    ) {
      proxy
        .$confirm('你的发票号或货单号为空，是否继续提交？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        })
        .then(() => {
          api(_formInfo).then((res) => {
            if (res && res.success) {
              proxy.$emit('returnModify')
              showDialog.value = false
            }
          })
          return
        })
        .catch(() => {
          return
        })
    } else {
      api(_formInfo).then((res) => {
        if (res && res.success) {
          proxy.$emit('returnModify')
          showDialog.value = false
        }
      })
    }
  })
}
function removeProduct(selectRow = undefined) {
  if (selectRow && selectRow.productId) {
    tableInfo.value.data = tableInfo.value.data.filter(
      (row) => row !== selectRow
    )
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.value.data = tableInfo.value.data.filter(
          (row) => !tableInfo.value.selections.includes(row)
        )
      })
  }
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = data
      break
  }
}
function addProduct() {
  productInfo.value.visible = true
  let ids = tableInfo.value.data.map((item) => {
    return item.productId
  })
  productInfo.value.query.saleId = formInfo.value.data.saleId
  productInfo.value.query.deliverId = formInfo.value.data.id
  productInfo.value.query.productIdNotIn = ids.toString()
}
function selectProduct(rows) {
  rows.forEach((item) => {
    if (item.codeType === 3) {
      item.flag = false
    }
  })
  tableInfo.value.data = rows.concat(tableInfo.value.data)
}
function getSaleMain() {
  getDeliverDetailBySaleId(props.saleOrderId).then((res) => {
    if (res && res.success) {
      let data = res.data
      if (data.mergeDetails.length) {
        data.mergeDetails.forEach((item) => {
          if (item.codeType === 3) {
            item.flag = false
          }
          item.sterilizationNumber = ''
        })
        tableInfo.value.data = data.mergeDetails
      }
      formInfo.value.data = res.data
    }
  })
}
function getMain() {
  getDeliverOrderById(props.orderId).then((res) => {
    if (res && res.success) {
      formInfo.value.data = res.data
    }
  })
}
function getList() {
  mergeDeliverOrderDetail({ orderId: props.orderId }).then((res) => {
    if (res && res.success) {
      if (res.data.length) {
        res.data.forEach((item) => {
          if (item.codeType === 3) {
            item.flag = true
          }
        })
      }
      let spanArr = res.data.concat([])
      spanArr.sort(compare('productId'))
      tableInfo.value.data = spanArr
    }
  })
}

onMounted(() => {
  if (props.saleOrderId) {
    getSaleMain()
  } else if (props.orderId) {
    getMain()
    getList()
  }
  formRefs.value = [proxy.$refs['tableForm'], formInfo.value.ref]
})
</script>
